
function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (status)
        return shader;
    console.log(gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
}

function createProgram(vertexShader, fragmentShader) {
    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    const status = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (status)
        return program;
    console.log(gl.getProgramInfoLog(program));
    gl.deleteProgram(program);
}

function flushAttrBuffer (program, shaderVar, bufferData) {
    let attrLocation = gl.getAttribLocation(program, shaderVar);
    let positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, bufferData, gl.STATIC_DRAW);
    gl.enableVertexAttribArray(attrLocation);
    return attrLocation;
}

function recycleBuffer() {
    gl.bindBuffer(gl.ARRAY_BUFFER, null);
    // TODO:
    // gl.deleteBuffer(positionBuffer);
}

function getProgram() {
    let vertexShaderSource = document.getElementById("vertex-shader").text;
    let fragmentShaderSource = document.getElementById("fragment-shader").text;
    let vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
    let fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
    let program = createProgram(vertexShader, fragmentShader);
    return program;
}

function getGlByCanvasId(canvasId) {
    let canvas = document.getElementById(canvasId);
    let gl = canvas.getContext("webgl");
    if (!gl) {
        console.log("can not use webgl");
    }else {
        return gl;
    }
}
